// xmonitor.go
package main

import (
	"flag"
	"fmt"
	"log"
	//"regexp"
	//	"os/exec"
	//_ "github.com/icattlecoder/godaemon"
	"net"
	"os"
	"runtime"
	"strings"
	"time"
)

const (
	ServerPort = "9911"
)

func GetSysInfo() {
	fmt.Println("sys")
}

func DelLog() {
	d, _ := time.ParseDuration("-24h")
	var dellogtime = time.Now().Add(d * 30).Format("20060102")
	err := os.Remove("xmonitor." + dellogtime + ".log")
	if err != nil {
		fmt.Println("delete log xmonitor." + dellogtime + ".log failure!")
	}
}

func PrintLog(logcontent string) {
	var logtime = time.Now().Format("20060102")
	var logFileName = "xmonitor." + logtime + ".log"
	runtime.GOMAXPROCS(runtime.NumCPU())
	logFile, err := os.OpenFile(logFileName, os.O_CREATE|os.O_RDWR|os.O_APPEND, 0666)
	if err != nil {
		fmt.Println("can't write log!")
		return
	}
	defer logFile.Close()
	gLogger := log.New(logFile, "\r\n", log.Ldate|log.Ltime)
	gLogger.Printf(": %v \n", logcontent)
}

func DaemonRun(t1, t2 *time.Ticker) {
	go func() {
		for {
			select {
			case <-t1.C:
				PrintLog("daemon")
			case <-t2.C:
				DelLog()
			}
		}
	}()
	tcpAddr, _ := net.ResolveTCPAddr("tcp4", "0.0.0.0:"+ServerPort)
	tcpListener, err := net.ListenTCP("tcp4", tcpAddr)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer tcpListener.Close()
	for {
		tcpConn, err := tcpListener.Accept()
		if err != nil {
			fmt.Println(err.Error())
		}
		go func() {
			for {
				_, err := tcpConn.Write([]byte("Daemon ok"))
				if err != nil {
					defer tcpConn.Close()
					return
				}
				time.Sleep(2 * time.Second)
			}
		}()
	}
}

func LiveRun(t1 *time.Ticker) {
	select {
	case <-t1.C:
		log.Println("live")
	}
}

func RemoteRun(t1 *time.Ticker) {
	select {
	case <-t1.C:
		log.Println("remote")
	}
}

func ClientRun(serverip string, count int) {
	tcpAddr, _ := net.ResolveTCPAddr("tcp4", serverip+":"+ServerPort)
	client, err := net.DialTCP("tcp4", nil, tcpAddr)
	if err != nil {
		fmt.Println(err.Error())
		return
	}
	defer client.Close()
	buf := make([]byte, 1024)
	for i := 0; i < count; i++ {
		log.Println("client")
		c, err := client.Read(buf)
		if err != nil {
			fmt.Println("connect failure")
			return
		} else {
			fmt.Println(string(buf[0:c]))
		}
	}

}

func HelpUsage() {
	fmt.Println("Usage:./xmonitor   print local info")
	fmt.Println("Usage:./xmonitor -l=3   print local info,interval is 3s")
	fmt.Println("Usage:./xmonitor --ip=192.168.1.1   print 192.168.1.1 info")
	fmt.Println("Usage:./xmonitor -clearlog=7  clear 7 days before the log")
	fmt.Println("Usage:./xmonitor -e  edit /home/Agent/etc/xmonitor.conf")
}

func main() {
	var Interval int
	var Rip string
	var Clearlog int
	var Count int
	flag.StringVar(&Rip, "ip", "", "client ip")
	//by := flag.String("by", "", "print define field in load,mem,swap,disk,io")
	flag.IntVar(&Clearlog, "clearlog", 0, "clear xmonitor log")
	help := flag.Bool("h", false, "show help info")
	edit := flag.Bool("e", false, "edit xmonitor conf")
	daemon := flag.Bool("d", false, "run in daemon mode")
	flag.IntVar(&Interval, "l", 2, "default the value is 2")
	flag.IntVar(&Count, "c", 14400, "default the value is 2")
	flag.Parse()

	if *help {
		HelpUsage()
		return
	}

	if *edit {
		//runout := exec.Command("vim", "/home/Agent/etc/xmonitor.conf")
		fmt.Println("edit")
		return
	}

	if Clearlog > 0 {
		//var cmd string = "find"
		//var args string = "/var/log/xmonitor/ -name xmonitor.* -type f -mtime +7 -exec rm -f {} ;"
		//runout := exec.Command(cmd, args)
		fmt.Printf("清除%d天前的数据\n", Clearlog)
		return
	}

	tlive := time.NewTicker(time.Duration(Interval) * time.Second)
	tdaemon := time.NewTicker(60 * time.Second)
	tdellog := time.NewTicker(24 * time.Hour)
	if Rip != "" {
		/*if strings.Contains(Rip, "192.168.") == false {
			//reg:=regexp.MustCompile("1[0-9]{2}|2[0-4][0-9]|25[0-5]|[1-9]?[0-9])\.(1[0-9]{2}|2[0-4][0-9]|25[0-5]|[1-9]?[0-9])\.(1[0-9]{2}|2[0-4][0-9]|25[0-5]|[1-9]?[0-9])\.(1[0-9]{2}|2[0-4][0-9]|25[0-5]|[1-9]?[0-9]")
			//reg := regexp.MustCompile("(\\d){1,3}.(\\d){1,3}$")
			//if reg.MatchString(Rip) {
			var rip1 string = "192.168." + Rip
			ClientRun(rip1, Count)
		} else {
			var rip1 string = Rip
			ClientRun(rip1, Count)
		}*/
		//fmt.Println(len(strings.Split(Rip,",")[])
		//fmt.Println(strings.Split(Rip,",")[0])
		tt := strings.Split(Rip, ",")
		fmt.Printf("%q\n", tt)
		fmt.Println(len(tt))

	}

	if *daemon {
		/*args := os.Args[1:]
		cmd := exec.Command(os.Args[0], args...)
		cmd.Start()
		fmt.Println("[PID]", cmd.Process.Pid)
		os.Exit(0)*/
		DaemonRun(tdaemon, tdellog)
	}

	if flag.NFlag() == 0 || (flag.NFlag() == 1 && (Interval >= 1 || Count > 0) && Rip == "") || (flag.NFlag() == 2 && Interval >= 1 && Count > 0 && Rip == "") {
		fmt.Println(flag.NFlag())
		for i := 0; i < Count; i++ {
			LiveRun(tlive)
			//DelLog()
		}
	}
}
